import 'dart:io';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

///
/// Dio下载Demo
/// https://github.com/flutterchina/dio/blob/flutter/README-ZH.md
///
class DioDownloadTest extends StatefulWidget {
  @override
  _DioDownloadTestState createState() => _DioDownloadTestState();
}

class _DioDownloadTestState extends State<DioDownloadTest> {
  String _responseText="";

  @override
  void initState() {
    super.initState();

    downloadImage();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Dio下载Demo'),
      ),
      body: Center(
        child: Text(_responseText),
      ),
    );
  }

  downloadImage() {
    var dio = new Dio();
    dio.onHttpClientCreate = (HttpClient client) {
      client.idleTimeout = new Duration(seconds: 0);
    };

    // This is big file(about 200M)
    // var url = "http://download.dcloud.net.cn/HBuilder.9.0.2.macosx_64.dmg";

    // This is a image, about 4KB
    var url = "https://www.baidu.com/img/bd_logo1.png";
    //var url="https://cdn.pixabay.com/photo/2018/09/03/23/56/sea-3652697_640.jpg?attachment";
    try {
      dio.download(url, "download-baidu.png",
          // Listen the download progress.
          onProgress: (received, total) {
        print((received / total * 100).toStringAsFixed(0) + "%");
      }).then((Response response) {
        setState(() {
          _responseText =
              "statusCode: ${response.statusCode}, download succeed!";
        });
      });
    } catch (e) {
      setState(() {
        _responseText = "ERROE: download[$url] throw exception!";
      });
    }
  }
}
